#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time    : 2021/10/19
# @Author  : ZhangAiqiang
# @FileName: voltage.py
import socket
from devTest import HVMsg
from database import HVData
import argparse
import json, os
import threading,time

# def test(number, hvdata):
def test(number, hvdata, ip=None):
    if ip==None:
        ip = hvdata.getIpByNumber(number)
    return queryAndStore(number, ip, 4001, hvdata)
def queryAndStore(number:str, ip, port, hvdata: HVData):
    print('query ip:{}'.format(ip))
    try:
        with HVMsg(ip, port,[]) as hv:
            hv.connect()
            hv.sendHexRequest()
            temper, fans_rpm, present_time, accumulated_time = hv.sendCaseStatusQueryCmd()
            channelInfo = hv.sendQueryAllChannelCmd()
            # hv.sendTextRequest()
        # id = hvdata.storeHV(ip,temper,fans_rpm, present_time, accumulated_time)
        # for j,chinfo in enumerate(channelInfo):
        #     hvdata.storeCh(id,j+1,chinfo)
            alarm = hvdata.storeInfo(number,temper, fans_rpm, present_time, accumulated_time,channelInfo)
            return alarm
    except ConnectionRefusedError:
        print('connectioin refused! failed query ip:{}'.format(ip))
        return []
def query(ip):
    try:
        with HVMsg(ip, 4001,[]) as hv:
            hv.connect()
            hv.sendHexRequest()
            temper, fans_rpm, present_time, accumulated_time = hv.sendCaseStatusQueryCmd()
            channelInfo = hv.sendQueryAllChannelCmd()
            #hv.sendTextRequest()
    except ConnectionRefusedError:
        print('connectioin refused! failed query ip:{}'.format(ip))
        return None
    except TimeoutError:
        print('timeout query ip:{}'.format(ip))
        channelInfo = []
        temper, fans_rpm, present_time, accumulated_time = 0, 0, 0, 0
        for i in range(25):
            faultcode, output, m_err, m_running, red_led, green_led, s_err, s_running,red_led1,green_led1 = 1, 1, 1, 1, 1, 0, 1, 0, 1, 0
            channelInfo.append([faultcode, output, m_err, m_running, red_led, green_led, s_err, s_running,red_led1,green_led1, -1, -1])
    return [temper, fans_rpm, present_time, accumulated_time,channelInfo]
def queryCh(ip,ch):
    try:
        with HVMsg(ip, 4001,[]) as hv:
            hv.connect()
            #hv.sendHexRequest()
            channelInfo = hv.sendQueryChannelCmd(ch)
    except ConnectionRefusedError:
        print('connectioin refused! failed query ip:{}'.format(ip))
        return []
    except TimeoutError:
        print('timeout query ip:{}'.format(ip))
        return []
    return channelInfo

def control(ip, open=True,master=True):
    try:
        with HVMsg(ip, 4001,[]) as hv:
            hv.connect()
            #hv.sendHexRequest()
            if open:
                hv.openAll()
            else:
                hv.closeAll()
            # hv.sendTextRequest()
    except ConnectionRefusedError:
        print('failed query ip:{}'.format(ip))
        return
    return
def controlCh(ip, ch, open=True,master=True):
    try:
        with HVMsg(ip, 4001,[]) as hv:
            hv.connect()
            #hv.sendHexRequest()
            if master:
                if open:
                    hv.sendControlChannelCmd(ch)
                else:
                    hv.sendControlChannelCmd(ch,False)
            else:
                if open:
                    hv.sendControlChannelCmd(ch,False,True)
                else:
                    hv.sendControlChannelCmd(ch,False,False)
            # hv.sendTextRequest()
    except ConnectionRefusedError:
        print('failed query ip:{}'.format(ip))
        return
    return
def testAll(configs, ips):
    numbers = configs['ip']
    hvdata=HVData(configs)
    alarms = []
    for i, (stack, ip) in enumerate(zip(numbers, ips)):
        print('query stack:{}'.format(stack))
        tempalarms = test(stack, hvdata, ip)
        alarms += tempalarms
    return alarms
if __name__=='__main__':
    psr = argparse.ArgumentParser()
    # psr.add_argument('--ip', dest='opt', type=str, help='output file')
    # psr.add_argument('ipt', type=str, help='input file')
    args = psr.parse_args()
    with open('./config.json','r') as ipt:
        configs = json.load(ipt)
    while(True):
    # t1 = threading.Timer(60,testAll,args=configs.ip)
    # t1.start()
        testAll(configs)
        time.sleep(60)


